package top.marken.onlineclass.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.marken.onlineclass.dao.UserMapper;
import top.marken.onlineclass.model.entity.User;
import top.marken.onlineclass.model.request.LoginRequest;
import top.marken.onlineclass.service.UserService;
import top.marken.onlineclass.util.JWTUtil;
import top.marken.onlineclass.util.JsonData;
import top.marken.onlineclass.util.MD5Util;

import java.util.Date;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {
    private static final String [] headImg = {
            "https://makun-ing-image-bed.oss-cn-chengdu.aliyuncs.com/hexo-gitee-blog/head/hexo-theme-butterfly.png",
            "https://makun-ing-image-bed.oss-cn-chengdu.aliyuncs.com/hexo-gitee-blog/head/jiaxinxiaobinggan.png",
            "https://makun-ing-image-bed.oss-cn-chengdu.aliyuncs.com/hexo-gitee-blog/head/octopus.jpg",
            "https://makun-ing-image-bed.oss-cn-chengdu.aliyuncs.com/hexo-gitee-blog/head/oldhead.png"
    };

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByPhone(String phone) {
        return userMapper.findByPhone(phone);
    }

    @Override
    public int addOne(Map<String, String> userInfo) {
        User user = parseUser(userInfo);
        if (user == null) {
            return JsonData.CODE_FAIL;
        }
        if (userMapper.insertOne(user) == 1) {
            return JsonData.CODE_SUCCESS;
        } else {
            return JsonData.CODE_ERROR;
        }
    }

    @Override
    public String login(LoginRequest loginRequest) {
        String phone = loginRequest.getPhone();
        String pwd = loginRequest.getPwd();

        User user = userMapper.findByPhone(phone);
        if (user == null) {
            return null;
        }
        if (user.getPwd().equals(MD5Util.MD5(pwd))) {
            return JWTUtil.generateJWT(user);
        }
        return null;
    }

    /**
     * 通过Userid来查找user
     * @param userId
     * @return
     */
    @Override
    public User findById(int userId) {
        return userMapper.findById(userId);
    }

    /**
     * 将具有User信息的map集合转化为User
     * @param userInfo
     * @return
     */
    private User parseUser(Map<String, String> userInfo) {
        if (userInfo.containsKey("name") && userInfo.containsKey("pwd") && userInfo.containsKey("phone")) {
            User user = new User();
            user.setName(userInfo.get("name"));
            // md5加密密码
            user.setPwd(MD5Util.MD5(userInfo.get("pwd")));
            user.setPhone(userInfo.get("phone"));
            user.setCreateTime(new Date());
            int index = new Random().nextInt(headImg.length);
            user.setHeadImg(headImg[index]);
            return user;
        }
        return null;
    }
}
